// Define the analog pin const int analogPin = A0; // Constants for converting the analog reading to distance const int minDistance = 10; // Minimum distance the sensor can measure in cm const int maxDistance = 80; // Maximum distance the sensor can measure in cm const float minVoltage = 0.4; // Minimum voltage at 10 cm (0.4V) const float maxVoltage = 3.1; // Maximum voltage at 80 cm (3.1V) void setup() { Serial.begin(9600); // Initialize serial communication } void loop() { // Read the analog voltage from the sensor int sensorValue = analogRead(analogPin); float voltage = sensorValue * (5.0 / 1023.0); // Convert the reading to voltage // Print the raw sensor value and voltage for debugging Serial.print("Sensor Value: "); Serial.print(sensorValue); Serial.print(" Voltage: "); Serial.print(voltage); Serial.println(" V"); // Convert the analog reading to a distance in centimeters float distance = convertVoltageToDistance(voltage); // Print the distance to the serial monitor Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); delay(500); // Wait 500 milliseconds before the next reading } // Function to convert voltage to distance float convertVoltageToDistance(float voltage) { float distance; // If voltage is outside the expected range, set it to max/min distance if (voltage <= minVoltage) { distance = minDistance; } else if (voltage >= maxVoltage) { distance = maxDistance; } else { // Convert voltage to distance based on a linear approximation distance = 27.86 / (voltage - 0.42); } return distance; }